package com.kay.json;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.*;
import java.util.stream.Collectors;

/**
 * @author Kay
 * @Date: 2019/11/28 18:30
 */
@WebServlet(urlPatterns = {"/json"})
public class JsonServlet extends HttpServlet {

    private static final String URL = "jdbc:h2:~/JavaEE-demo;MODE=MYSQL;DB_CLOSE_DELAY=-1";
    private static final String NAME = "sa";
    private static final String PASSWORD = "sa";

    // curl -v http://localhost:8080/JavaEE-demo/json
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        StudentDTO studentDTO = new StudentDTO("叶镁琪get", 21);

        // 要获取对象的JSON表示，我们需要使用JsonbBuilder类及其toJson（）方法。
        Jsonb jsonb = JsonbBuilder.create();
        String jsonStudent = jsonb.toJson(studentDTO);

        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        resp.getWriter().println(jsonStudent);
    }


    // 获取前端post提交的json字符串，并转换为对象；再把对象转为json字符串，生成响应返回前端。
    // curl -v -H "Content-Type: application/json" http://localhost:8080/JavaEE-demo/json -X POST --data '{"姓名":"叶镁琪","年龄":21}'
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Jsonb jsonb = JsonbBuilder.create();
        String postJsonString = new BufferedReader(new InputStreamReader(req.getInputStream()))
                                                            .lines().collect(Collectors.joining(System.lineSeparator()));

        // 利用jsonb把json字符串转换为对象
        StudentDTO studentDTO = jsonb.fromJson(postJsonString, StudentDTO.class);

        try (Connection conn = DriverManager.getConnection(URL, NAME, PASSWORD)) {
            Statement stmt = conn.createStatement();
            stmt.executeUpdate(
                    "CREATE TABLE IF NOT EXISTS `student` (" +
                            "  `id` int(11) unsigned NOT NULL AUTO_INCREMENT," +
                            "  `name` varchar(100) NOT NULL," +
                            "  `age` int(11) NOT NULL," +
                            "  PRIMARY KEY (`id`)" +
                            ");"
            );

            stmt.executeUpdate(
                    "insert into `student` (`name`,`age`) values ('"
                            + studentDTO.getName() + "', "
                            + studentDTO.getAge() + ");"
            );

            ResultSet rs = stmt.executeQuery("select * from student");

            while (rs.next()) {
                System.out.println(rs.getString("id") + "," + rs.getString("name") + "," + rs.getInt("age"));
            }
        }catch (SQLException e) {
            e.printStackTrace();
        }

        // 如果保存数据正确，返回一个json回前端：{"code":0,"msg":"操作成功"}
        String jsonStudent = "{\"code\":0,\"msg\":\"操作成功\"}";
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        resp.getWriter().println(jsonStudent);
    }
}
